package apitemplate

import (
	"bytes"
	"io"
	"time"

	"gitcode.com/riteny/go-logfct"
	"github.com/gin-gonic/gin"
)

var logger = logfct.New("api")

func LogTracerMiddleware(c *gin.Context) {

	start := time.Now()

	bodyBytes, _ := io.ReadAll(c.Request.Body)

	bodyString := string(bodyBytes)
	c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
	logger.Infof("Request URL: %s ,Request Body: %v", c.Request.URL, bodyString)

	blw := &bodyLogWriter{
		ResponseWriter: c.Writer,
		body:           bytes.NewBufferString(""),
	}

	c.Writer = blw

	c.Next()

	if blw.body.Len() > 0 {
		logger.Infof("Response URL: %s ,Response body: %v ,usedTime:%d ms", c.Request.URL, string(blw.body.Bytes()), time.Since(start).Milliseconds())
	} else {
		logger.Infof("Response URL: %s ,Response body: %v ,usedTime:%d ms", c.Request.URL, "", time.Since(start).Milliseconds())
	}
}

type bodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}
